package service;

import common.Exception.Result;
import common.Exception.Results;
import dto.req.AuthorDeleteArticleReqDTO;
import dto.req.AuthorPublishArticleReqDTO;
import dto.req.UpdateArticleContextReqDTO;
import dto.req.UpdateArticleTitleReqDTO;
import dto.resp.AdminQueryWaitViewArticleRespDTO;
import dto.resp.QueryOneArticleByIdRespDTO;
import entity.ArticleDO;
import entity.AuthorDO;
import service.impl.ArticleServiceImpl;
import util.JDBCUtils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class ArticleService implements ArticleServiceImpl {
    private static final String tableName = " article ";
    private static final int limtiNum = 5;

    private boolean checkArticle(AuthorPublishArticleReqDTO articleDO) {
        //TODO 数据校验
        if (null == articleDO) {
            throw new Result("错误？实体类为空");
        }
        if (articleDO.getAuthorId() == null
                || articleDO.getTitle() == null
                || articleDO.getContext() == null) {
            throw new Result("错误，实体参数具有空值");
        }
        if (articleDO.getTitle().length() < 5) {
            throw new Result("标题不能少于5个字");
        }
        if (articleDO.getContext().length() < 10) {
            throw new Result("正文内容不能低于10个字");
        }
        return true;
    }

    @Override
    public boolean addArticle(AuthorPublishArticleReqDTO articleDO) {
        Connection connection = null;
        try {
            checkArticle(articleDO);
            connection = JDBCUtils.getConnection();
            //Statement statement = connection.createStatement();
            String sql = "INSERT INTO " + tableName + "(author_id, title,context,click_favorite,visitor,create_date,update_date) VALUES (?, ?,?,?,?,?,?)";
           // String sql = "INSERT INTO " + tableName + "(username, password,name) VALUES (?, ?,?)";

            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleDO.getAuthorId());
            pstmt.setString(2, articleDO.getTitle());
            pstmt.setString(3, articleDO.getContext());
            pstmt.setInt(4, 0);
            pstmt.setInt(5, 0);
            pstmt.setDate(6, new Date(System.currentTimeMillis()));
            pstmt.setDate(7, new Date(System.currentTimeMillis()));

            // 执行SQL语句
            pstmt.executeUpdate();
            JDBCUtils.closeResource(connection, pstmt);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e.getMessage());
            //return false;
        }
    }

    @Override
    public Results updateArticleTitle(UpdateArticleTitleReqDTO request) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        Results results = new Results();
        try {
            if (request.getArticleId() == null) {
                return results.fail("文章Id为空");
            }
            if (request.getNewTitle() == null || request.getNewTitle().length() < 6) {
                return results.fail("标题不得少于6个字");
            }
            if (request.getAuthorId() == null) {
                return results.fail("作者不存在");
            }

            connection = JDBCUtils.getConnection();
            String sql = "UPDATE " + tableName + " SET title = ?,update_date = ? WHERE author_id = ? AND id = ? ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, request.getNewTitle());
            pstmt.setDate(2, new Date(System.currentTimeMillis()));
            pstmt.setInt(3, request.getAuthorId());
            pstmt.setInt(4, request.getArticleId());

            // 执行SQL语句
            pstmt.executeUpdate();
            return results.success("修改成功");
        } catch (Exception e) {
            return results.fail("修改文章标题异常: " + e.getMessage());
        } finally {
            JDBCUtils.closeResource(connection, pstmt);
        }
    }

    @Override
    public Results updateArticleContext(UpdateArticleContextReqDTO request) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        Results results = new Results();
        try {
            if (request.getArticleId() == null) {
                return results.fail("文章id为空！");
            }
            if (request.getNewContext() == null || request.getNewContext().length() < 10) {
                return results.fail("正文不得少于10个字符");
            }
            if (request.getAuthorId() == null) {
                return results.fail("作者不存在");
            }

            connection = JDBCUtils.getConnection();
            String sql = "UPDATE " + tableName + " SET context = ?,update_date = ? WHERE author_id = ? AND id = ? ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, request.getNewContext());
            pstmt.setDate(2, new Date(System.currentTimeMillis()));
            pstmt.setInt(3, request.getAuthorId());
            pstmt.setInt(4, request.getArticleId());

            // 执行SQL语句
            pstmt.executeUpdate();

            return results.success("修改正文成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return results.fail("修改正文异常: " + e.getMessage());

        } finally {
            JDBCUtils.closeResource(connection, pstmt);

        }
    }

    /**
     * 用户删除文章接口
     * @param
     * @return
     */
    @Override
    public Results deleteArticle(AuthorDeleteArticleReqDTO articleDTO) {
        Results results = new Results();
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            if (articleDTO.getArticleId() == null) {
               return  results.fail("文章id为空！");
            }
            if (articleDTO.getAuthorId() == null) {
                return  results.fail("作者不存在");
            }
            connection = JDBCUtils.getConnection();
            String sql = "UPDATE " + tableName + " SET is_delete = 1 WHERE id = ? AND author_id = ? ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleDTO.getArticleId());
            pstmt.setInt(2, articleDTO.getAuthorId());

            // 执行SQL语句
            pstmt.executeUpdate();
            return  results.success("删除成功");
        } catch (Exception e) {
            return  results.fail("删除失败，异常: " + e.getMessage());
        } finally {
            JDBCUtils.closeResource(connection, pstmt);
        }
    }


    /**
     * 管理员删除文章接口，管理员有权限删除不用关心该文章是谁第
     * @param
     * @return
     */
    public Results deleteArticleByAdmin(Integer id){
        Results results = new Results();
        //这里应该做一个管理员身份校验??
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            if (id == null) {
               return results.fail("文章id为空！");
            }
            connection = JDBCUtils.getConnection();
            String sql = "UPDATE " + tableName + " SET is_delete = 1  WHERE id = ?  ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, id);

            // 执行SQL语句
            pstmt.executeUpdate();
            return results.success("删除成功");
        } catch (Exception e) {
            return results.fail("删除失败，失败异常: " + e.getMessage());
        } finally {
            JDBCUtils.closeResource(connection, pstmt);
        }
    }

    @Override
    public Results<ArrayList<QueryOneArticleByIdRespDTO>> queryAllArticleByAuthorId(Integer authorId) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<QueryOneArticleByIdRespDTO> articles = new ArrayList<>();
        Results<ArrayList<QueryOneArticleByIdRespDTO>> results = new Results<>();
        try {
            if (authorId == null) {
                return results.fail("用户不存在");
            }
            //应该先查询用户是否存在？？？

            connection = JDBCUtils.getConnection();
            String sql = "SELECT id,author_id,title,context,click_favorite,visitor,is_view,create_date,update_date FROM " + tableName + " WHERE author_id = ? AND is_delete = 0 ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, authorId);

            // 执行SQL语句
            rs = pstmt.executeQuery();
            if (!rs.next()) {
                //用户不存在
                return results.fail("没有搜索到结果哦");
            }
            do {
                QueryOneArticleByIdRespDTO articleDO = new QueryOneArticleByIdRespDTO();
                articleDO.setId(rs.getInt(1));
                articleDO.setAuthorId(rs.getInt(2));
                articleDO.setTitle(rs.getString(3));
                articleDO.setContext(rs.getString(4));
                articleDO.setClickFavorite(rs.getInt(5));
                articleDO.setVisitor(rs.getInt(6));
                articleDO.setIsView(rs.getInt(7));
                articleDO.setCreateDate(rs.getDate(8));
                articleDO.setUpdateDate(rs.getDate(9));
                articles.add(articleDO);
            } while (rs.next());
            results.setData(articles);
            return results.success("查询成功");
        } catch (Exception e) {
           return results.fail(e.getMessage());
        } finally {
            JDBCUtils.closeResource(connection, pstmt, rs);
        }
    }

    /**
     * 查看已经审核过的文章
     *
     * @param articleId
     * @return
     */
    @Override
    public Results<QueryOneArticleByIdRespDTO> queryOneArticleById(Integer articleId) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Results<QueryOneArticleByIdRespDTO> results = new Results<>();
        QueryOneArticleByIdRespDTO articleDO = null;
        try {
            if (articleId == null) {
                return results.fail("文章Id为空");
            }

            connection = JDBCUtils.getConnection();
            String sql = "SELECT id,author_id,title,context,click_favorite,visitor,is_view,create_date,update_date FROM " + tableName + " WHERE id = ? AND is_view = 1 AND is_delete = 0 ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleId);

            // 执行SQL语句
            rs = pstmt.executeQuery();
            if (!rs.next()) {
                return results.fail("文章不存在");
            }
            articleDO = new QueryOneArticleByIdRespDTO();
            articleDO.setId(rs.getInt(1));
            articleDO.setAuthorId(rs.getInt(2));
            articleDO.setTitle(rs.getString(3));
            articleDO.setContext(rs.getString(4));
            articleDO.setClickFavorite(rs.getInt(5));
            articleDO.setVisitor(rs.getInt(6));
            articleDO.setIsView(rs.getInt(7));
            articleDO.setCreateDate(rs.getDate(8));
            articleDO.setUpdateDate(rs.getDate(9));
            //添加一次访客
            boolean b = addVisitor(articleId);
            if (!b) {
                //允许访客出现少量丢失，打印日志提醒一下即可
                System.out.println("添加访客失败");
            }
            articleDO.setVisitor(articleDO.getVisitor() + 1);
            results.setData(articleDO);
            return results.success("查询成功");
        } catch (Exception e) {
           return results.success("根据ID查询文章异常: " + e.getMessage());
        } finally {
            JDBCUtils.closeResource(connection, pstmt, rs);
        }
    }

    @Override
    public boolean clickFavorite(Integer articleId) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {


            connection = JDBCUtils.getConnection();
            String sql = "UPDATE " + tableName + " SET click_favorite =  click_favorite + 1 WHERE id = ? ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleId);

            // 执行SQL语句
            pstmt.executeUpdate();
            return true;
        } catch (Exception e) {
            System.out.println("点赞添加出现异常： " + e.getMessage());
            return false;
        } finally {
            JDBCUtils.closeResource(connection, pstmt);

        }
    }


    @Override
    public Results viewArticle(Integer articleId) {
        Results results = new Results();
        if (articleId == null) {
            return results.fail("文章Id不存在");
        }
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
        connection = JDBCUtils.getConnection();
        String sql = "UPDATE " + tableName + " SET is_view = ? WHERE id = ? ";
        pstmt = connection.prepareStatement(sql);
        pstmt.setInt(1, 1);
        pstmt.setInt(2, articleId);
        // 执行SQL语句
        pstmt.executeUpdate();
        return results.success("审核成功");
    } catch(Exception e) {
        System.out.println(e.getMessage());
        return results.fail("审核出现异常");
    } finally {
        JDBCUtils.closeResource(connection, pstmt);
    }

}

    @Override
    public Results<ArrayList<AdminQueryWaitViewArticleRespDTO>> queryWaitViewArticleAll(Integer idx) {
        Results<ArrayList<AdminQueryWaitViewArticleRespDTO>> results = new Results<>();
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        if(idx < 1){
            return results.fail("无法继续上一页");
        }
        ArrayList<AdminQueryWaitViewArticleRespDTO> articles = new ArrayList<>();
        try {
            connection = JDBCUtils.getConnection();
            String sql = "SELECT  id,author_id,title,context,is_view FROM  " +
                    tableName + " WHERE is_view = 0 AND is_delete = 0 limit ?," + String.valueOf(limtiNum);
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, (idx - 1) * limtiNum );

            // 执行SQL语句
            rs = pstmt.executeQuery();
            if (!rs.next()) {
                //用户不存在
                return results.fail("当前没有待审核文章");
            }
            do {
                AdminQueryWaitViewArticleRespDTO article = new AdminQueryWaitViewArticleRespDTO();
                article.setId(rs.getInt(1));
                article.setAuthorId(rs.getInt(2));
                article.setTitle(rs.getString(3));
                article.setContext(rs.getString(4));
                article.setIsView(rs.getInt(5));
                articles.add(article);
            } while (rs.next());
            results.setData(articles);
            return results.success("查询所有待审核文章成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(connection, pstmt, rs);
        }


    }

    private boolean addVisitor(Integer articleId) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "UPDATE " + tableName + " SET visitor =  visitor + 1 WHERE id = ? ";
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, articleId);

            // 执行SQL语句
            pstmt.executeUpdate();
            return true;
        } catch (Exception e) {
            System.out.println("访客添加出现异常： " + e.getMessage());
            return false;
        } finally {
            JDBCUtils.closeResource(connection, pstmt);

        }
    }




}

